package com.jdk.learn.juc._06multithreadsecurity;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by ricky
 * on 2018/1/31.
 * 解决多线程安全的几种方案：
 * 1.同步代码块
 * 2.同步方法
 * 3.使用锁
 */
public class TestSecurity {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "1好窗口").start();
        new Thread(ticket, "2好窗口").start();
        new Thread(ticket, "3好窗口").start();

    }
}

class Ticket implements Runnable {
    private int nums = 100;//总共一百张票

    private Lock lock = new ReentrantLock();

    /**
     * 安全的解决方案
     */
//    @Override
    public void run2() {
        while (true) {
            lock.lock();
            try {
                Thread.sleep(20);
                if (nums > 0) {
                    Thread.sleep(20);
                    System.out.println(Thread.currentThread().getName() + ",安全的还有" + --nums + "张票");
                } else {
                    System.out.println("-------票已经卖完了-------");
                    Thread.currentThread().interrupt();
                    break;
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 错误的示例
     */
    @Override
    public void run() {
        while (true) {
            try {
                if (nums > 0) {
                    Thread.sleep(20);
                    System.out.println(Thread.currentThread().getName() + ",还有" + --nums + "张票");
                } else {
                    System.out.println("-------票已经卖完了-------");
                    Thread.currentThread().interrupt();
                    break;
                }


            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 锁的示例
 */
class SynchronizedDemo {
    private int i = 0;

    private Lock lock = new ReentrantLock();

    /**
     * 同步方法
     *
     * @return
     */
    public synchronized int getValue() {
        i = i * i;
        return i;
    }


    /**
     * 同步方法
     *
     * @return
     */
    public int getValueNotMethod() {
        synchronized (this) {
            i = i * i;
            return i;
        }
    }


    /**
     * 使用锁
     *
     * @return
     */
    public int getValueNotMethod2() {
        try {
            lock.lock();
            i = i * i;
            return i;
        } finally {
            lock.unlock();
        }

    }


}
